/* ------------------------------ dom/node.js ------------------------------- */
VED.dom.node = VED.dom.domObject.extend({
   initialize: function( domNode ) {
      if ( domNode ) {
         var type = domNode.nodeType == VED.NODE_DOCUMENT ? 'document' : domNode.nodeType == VED.NODE_ELEMENT ? 'element' : domNode.nodeType == VED.NODE_TEXT ? 'text' : domNode.nodeType == VED.NODE_COMMENT ? 'comment' : domNode.nodeType == VED.NODE_DOCUMENT_FRAGMENT ? 'documentFragment' : 'domObject'; // Call the base constructor otherwise.

         return new VED.dom[ type ]( domNode );
      }

      return this;
   }
});

// VED.dom.node.prototype = new VED.dom.domObject();

VED.NODE_ELEMENT = 1;
VED.NODE_DOCUMENT = 9;
VED.NODE_TEXT = 3;
VED.NODE_COMMENT = 8;
VED.NODE_DOCUMENT_FRAGMENT = 11;

VED.POSITION_IDENTICAL = 0;
VED.POSITION_DISCONNECTED = 1;
VED.POSITION_FOLLOWING = 2;
VED.POSITION_PRECEDING = 4;
VED.POSITION_IS_CONTAINED = 8;
VED.POSITION_CONTAINS = 16;

VED.dom.node.implement({

   appendTo: function( element, toStart ) {
      element.append( this, toStart );
      return element;
   },

   clone: function( includeChildren, cloneId ) {
      var $clone = this.$.cloneNode( includeChildren );

      var removeIds = function( node ) {
            // Reset data-ved-expando only when has been cloned (IE and only for some types of objects).
            if ( node['data-ved-expando'] )
               node['data-ved-expando'] = false;

            if ( node.nodeType != VED.NODE_ELEMENT )
               return;
            if ( !cloneId )
               node.removeAttribute( 'id', false );

            if ( includeChildren ) {
               var childs = node.childNodes;
               for ( var i = 0; i < childs.length; i++ )
                  removeIds( childs[ i ] );
            }
         };

      // The "id" attribute should never be cloned to avoid duplication.
      removeIds( $clone );

      return new VED.dom.node( $clone );
   },

   hasPrevious: function() {
      return !!this.$.previousSibling;
   },

   hasNext: function() {
      return !!this.$.nextSibling;
   },

   insertAfter: function( node ) {
      node.$.parentNode.insertBefore( this.$, node.$.nextSibling );
      return node;
   },

   insertBefore: function( node ) {
      node.$.parentNode.insertBefore( this.$, node.$ );
      return node;
   },

   insertBeforeMe: function( node ) {
      this.$.parentNode.insertBefore( node.$, this.$ );
      return node;
   },

   getAddress: function( normalized ) {
      var address = [];
      var $documentElement = this.getDocument().$.documentElement;
      var node = this.$;

      while ( node && node != $documentElement ) {
         var parentNode = node.parentNode;

         if ( parentNode ) {
            // Get the node index. For performance, call getIndex
            // directly, instead of creating a new node object.
            address.unshift( this.getIndex.call({ $: node }, normalized ) );
         }

         node = parentNode;
      }

      return address;
   },

   getDocument: function() {
      return new VED.dom.document( this.$.ownerDocument || this.$.parentNode.ownerDocument );
   },

   getIndex: function( normalized ) {
      // Attention: getAddress depends on this.$
      // getIndex is called on a plain object: { $ : node }

      var current = this.$,
         index = -1,
         isNormalizing;

      if ( !this.$.parentNode )
         return index;

      do {
         // Bypass blank node and adjacent text nodes.
         if ( normalized && current != this.$ && current.nodeType == VED.NODE_TEXT && ( isNormalizing || !current.nodeValue ) ) {
            continue;
         }

         index++;
         isNormalizing = current.nodeType == VED.NODE_TEXT;
      }
      while ( ( current = current.previousSibling ) )

      return index;
   },

   getNextSourceNode: function( startFromSibling, nodeType, guard ) {
      // If "guard" is a node, transform it in a function.
      if ( guard && !guard.call ) {
         var guardNode = guard;
         guard = function( node ) {
            return !node.equals( guardNode );
         };
      }

      var node = ( !startFromSibling && this.getFirst && this.getFirst() ),
         parent;

      // Guarding when we're skipping the current element( no children or 'startFromSibling' ).
      // send the 'moving out' signal even we don't actually dive into.
      if ( !node ) {
         if ( this.type == VED.NODE_ELEMENT && guard && guard( this, true ) === false )
            return null;
         node = this.getNext();
      }

      while ( !node && ( parent = ( parent || this ).getParent() ) ) {
         // The guard check sends the "true" paramenter to indicate that
         // we are moving "out" of the element.
         if ( guard && guard( parent, true ) === false )
            return null;

         node = parent.getNext();
      }

      if ( !node )
         return null;

      if ( guard && guard( node ) === false )
         return null;

      if ( nodeType && nodeType != node.type )
         return node.getNextSourceNode( false, nodeType, guard );

      return node;
   },

   getPreviousSourceNode: function( startFromSibling, nodeType, guard ) {
      if ( guard && !guard.call ) {
         var guardNode = guard;
         guard = function( node ) {
            return !node.equals( guardNode );
         };
      }

      var node = ( !startFromSibling && this.getLast && this.getLast() ),
         parent;

      // Guarding when we're skipping the current element( no children or 'startFromSibling' ).
      // send the 'moving out' signal even we don't actually dive into.
      if ( !node ) {
         if ( this.type == VED.NODE_ELEMENT && guard && guard( this, true ) === false )
            return null;
         node = this.getPrevious();
      }

      while ( !node && ( parent = ( parent || this ).getParent() ) ) {
         // The guard check sends the "true" paramenter to indicate that
         // we are moving "out" of the element.
         if ( guard && guard( parent, true ) === false )
            return null;

         node = parent.getPrevious();
      }

      if ( !node )
         return null;

      if ( guard && guard( node ) === false )
         return null;

      if ( nodeType && node.type != nodeType )
         return node.getPreviousSourceNode( false, nodeType, guard );

      return node;
   },

   getPrevious: function( evaluator ) {
      var previous = this.$,
         retval;
      do {
         previous = previous.previousSibling;

         // Avoid returning the doc type node.
         // http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-412266927
         retval = previous && previous.nodeType != 10 && new VED.dom.node( previous );
      }
      while ( retval && evaluator && !evaluator( retval ) )
      return retval;
   },

   getNext: function( evaluator ) {
      var next = this.$,
         retval;
      do {
         next = next.nextSibling;
         retval = next && new VED.dom.node( next );
      }
      while ( retval && evaluator && !evaluator( retval ) )
      return retval;
   },

   getParent: function( allowFragmentParent ) {
      var parent = this.$.parentNode;
      return ( parent && ( parent.nodeType == VED.NODE_ELEMENT || allowFragmentParent && parent.nodeType == VED.NODE_DOCUMENT_FRAGMENT ) ) ? new VED.dom.node( parent ) : null;
   },

   getParents: function( closerFirst ) {
      var node = this;
      var parents = [];

      do {
         parents[ closerFirst ? 'push' : 'unshift' ]( node );
      }
      while ( ( node = node.getParent() ) )

      return parents;
   },

   getCommonAncestor: function( node ) {
      if ( node.equals( this ) )
         return this;

      if ( node.contains && node.contains( this ) )
         return node;

      var start = this.contains ? this : this.getParent();

      do {
         if ( start.contains( node ) ) return start;
      }
      while ( ( start = start.getParent() ) );

      return null;
   },

   getPosition: function( otherNode ) {
      var $ = this.$;
      var $other = otherNode.$;

      if ( $.compareDocumentPosition )
         return $.compareDocumentPosition( $other );

      // IE and Safari have no support for compareDocumentPosition.

      if ( $ == $other )
         return VED.POSITION_IDENTICAL;

      // Only element nodes support contains and sourceIndex.
      if ( this.type == VED.NODE_ELEMENT && otherNode.type == VED.NODE_ELEMENT ) {
         if ( $.contains ) {
            if ( $.contains( $other ) )
               return VED.POSITION_CONTAINS + VED.POSITION_PRECEDING;

            if ( $other.contains( $ ) )
               return VED.POSITION_IS_CONTAINED + VED.POSITION_FOLLOWING;
         }

         if ( 'sourceIndex' in $ ) {
            return ( $.sourceIndex < 0 || $other.sourceIndex < 0 ) ? VED.POSITION_DISCONNECTED : ( $.sourceIndex < $other.sourceIndex ) ? VED.POSITION_PRECEDING : VED.POSITION_FOLLOWING;
         }
      }

      // For nodes that don't support compareDocumentPosition, contains
      // or sourceIndex, their "address" is compared.

      var addressOfThis = this.getAddress(),
         addressOfOther = otherNode.getAddress(),
         minLevel = Math.min( addressOfThis.length, addressOfOther.length );

      // Determinate preceed/follow relationship.
      for ( var i = 0; i <= minLevel - 1; i++ ) {
         if ( addressOfThis[ i ] != addressOfOther[ i ] ) {
            if ( i < minLevel ) {
               return addressOfThis[ i ] < addressOfOther[ i ] ? VED.POSITION_PRECEDING : VED.POSITION_FOLLOWING;
            }
            break;
         }
      }

      // Determinate contains/contained relationship.
      return ( addressOfThis.length < addressOfOther.length ) ? VED.POSITION_CONTAINS + VED.POSITION_PRECEDING : VED.POSITION_IS_CONTAINED + VED.POSITION_FOLLOWING;
   },

   getAscendant: function( reference, includeSelf ) {
      var $ = this.$,
         name;

      if ( !includeSelf )
         $ = $.parentNode;

      while ( $ ) {
         if ( $.nodeName && ( name = $.nodeName.toLowerCase(), ( typeof reference == 'string' ? name == reference : name in reference ) ) )
            return new VED.dom.node( $ );

         $ = $.parentNode;
      }
      return null;
   },

   hasAscendant: function( name, includeSelf ) {
      var $ = this.$;

      if ( !includeSelf )
         $ = $.parentNode;

      while ( $ ) {
         if ( $.nodeName && $.nodeName.toLowerCase() == name )
            return true;

         $ = $.parentNode;
      }
      return false;
   },

   move: function( target, toStart ) {
      target.append( this.remove(), toStart );
   },

   remove: function( preserveChildren ) {
      var $ = this.$;
      var parent = $.parentNode;

      if ( parent ) {
         if ( preserveChildren ) {
            // Move all children before the node.
            for ( var child;
            ( child = $.firstChild ); ) {
               parent.insertBefore( $.removeChild( child ), $ );
            }
         }

         parent.removeChild( $ );
      }

      return this;
   },

   replace: function( nodeToReplace ) {
      this.insertBefore( nodeToReplace );
      nodeToReplace.remove();
   },

   trim: function() {
      this.ltrim();
      this.rtrim();
   },

   ltrim: function() {
      var child;
      while ( this.getFirst && ( child = this.getFirst() ) ) {
         if ( child.type == VED.NODE_TEXT ) {
            var trimmed = child.getText().ltrim(),
               originalLength = child.getLength();

            if ( !trimmed ) {
               child.remove();
               continue;
            } else if ( trimmed.length < originalLength ) {
               child.split( originalLength - trimmed.length );

               // IE BUG: child.remove() may raise JavaScript errors here. (#81)
               this.$.removeChild( this.$.firstChild );
            }
         }
         break;
      }
   },

   rtrim: function() {
      var child;
      while ( this.getLast && ( child = this.getLast() ) ) {
         if ( child.type == VED.NODE_TEXT ) {
            var trimmed = child.getText().rtrim(),
               originalLength = child.getLength();

            if ( !trimmed ) {
               child.remove();
               continue;
            } else if ( trimmed.length < originalLength ) {
               child.split( trimmed.length );

               // IE BUG: child.getNext().remove() may raise JavaScript errors here.
               // (#81)
               this.$.lastChild.parentNode.removeChild( this.$.lastChild );
            }
         }
         break;
      }

      if ( !VED.env.ie && !VED.env.opera ) {
         child = this.$.lastChild;

         if ( child && child.type == 1 && child.nodeName.toLowerCase() == 'br' ) {
            // Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#324).
            child.parentNode.removeChild( child );
         }
      }
   },

   isReadOnly: function() {
      var element = this;
      if ( this.type != VED.NODE_ELEMENT )
         element = this.getParent();

      if ( element && typeof element.$.isContentEditable != 'undefined' )
         return !( element.$.isContentEditable || element.data( 'ved-editable' ) );
      else {
         // Degrade for old browsers which don't support "isContentEditable", e.g. FF3

         while ( element ) {
            if ( element.data( 'ved-editable' ) )
               break;

            if ( element.getAttribute( 'contentEditable' ) == 'false' )
               return true;
            else if ( element.getAttribute( 'contentEditable' ) == 'true' )
               break;

            element = element.getParent();
         }

         // Reached the root of DOM tree, no editable found.
         return !element;
      }
   }
});





